package main

import (
	"embed"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"webrtc_server/pkg/server"
)

//go:embed static/*
var fileContent embed.FS

func main() {
	log.SetFlags(log.Lshortfile | log.LstdFlags)

	crt, key, _ := writeCert(fileContent)

	engine := server.NewWebRtcEngine(7000, fileContent)
	go engine.StartWebrtc(7001, crt, key)
	go engine.StartRtsp(8554, 8000, 8001)
	//go engine.StartRtp2Rtsp(5004)
	//go engine.StartFile2Rtsp(`F:\FFOutput\a\2.h264`)

	quitChan := make(chan os.Signal, 2)
	signal.Notify(quitChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
	<-quitChan
}

// writeCert 将证书写入文件
func writeCert(fileContent embed.FS) (crt string, key string, err error) {
	var appDir string

	if appDir, err = os.UserCacheDir(); err != nil {
		appDir = "."
	} else {
		appDir = fmt.Sprintf("%v/webrtc_server", appDir)
	}

	_ = os.MkdirAll(appDir, os.ModePerm)

	crt = fmt.Sprintf("%v/server.crt", appDir)
	crtData, _ := fileContent.ReadFile("static/server.crt")
	_ = os.WriteFile(crt, crtData, os.ModePerm)

	key = fmt.Sprintf("%v/server.key", appDir)
	keyData, _ := fileContent.ReadFile("static/server.key")
	_ = os.WriteFile(key, keyData, os.ModePerm)

	return crt, key, nil
}
